package com.tutk.P2PCam264;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tutk.IOTC.AVFrame;
import com.tutk.IOTC.AVIOCTRLDEFs;
import com.tutk.IOTC.AVIOCTRLDEFs.SMsgAVIoctrlGetSupportStreamReq;
import com.tutk.IOTC.AVIOCTRLDEFs.SStreamDef;
import com.tutk.IOTC.Camera;
import com.tutk.IOTC.CameraListener;
import com.tutk.IOTC.IMonitor;
import com.tutk.IOTC.IOTCAPIs;
import com.tutk.IOTC.IReceiveSnapshotListener;
import com.tutk.IOTC.IRegisterIOTCListener;
import com.tutk.IOTC.MediaCodecListener;
import com.tutk.IOTC.MediaCodecMonitor;
import com.tutk.IOTC.MediaCodecMonitor_MPEG4;
import com.tutk.IOTC.Monitor;
import com.tutk.IOTC.St_SInfo;
import com.tutk.Logger.Glog;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;

import cn.innosmart.aq.R;

public class LiveViewActivity extends AppCompatActivity implements
		IRegisterIOTCListener, CameraListener,
		IReceiveSnapshotListener, MediaCodecListener {

	private static final boolean DEBUG_REC = false;
	private static final int BUILD_VERSION_CODES_ICE_CREAM_SANDWICH = 14;
	private static final int STS_CHANGE_CHANNEL_STREAMINFO = 99;
	private static final int STS_SNAPSHOT_SCANED = 98;
	// private static final String FILE_TYPE = "image/*";

	private static final int REQUEST_CODE_ALBUM = 99;

//	private static final int OPT_MENU_ITEM_ALBUM = Menu.FIRST;
//	private static final int OPT_MENU_ITEM_SNAPSHOT = Menu.FIRST + 1;
//	// private static final int OPT_MENU_ITEM_SUBSTREAM = Menu.FIRST + 2;
//	private static final int OPT_MENU_ITEM_AUDIOCTRL = Menu.FIRST + 2;
//	private static final int OPT_MENU_ITEM_AUDIO_IN = Menu.FIRST + 3;
//	private static final int OPT_MENU_ITEM_AUDIO_OUT = Menu.FIRST + 4;
//	private static final int OPT_MENU_ITEM_RECORD = Menu.FIRST + 6;

	private final int THUMBNAIL_LIMIT_HEIGHT = 720;
	private final int THUMBNAIL_LIMIT_WIDTH = 1280;

	// private TouchedMonitor monitor = null;
//	private IMonitor monitor = null;
	private IMonitor mSoftMonitor = null;
	private IMonitor mHardMonitor = null;
	private MyCamera mCamera = null;
	private DeviceInfo mDevice = null;

	private String mDevUID;
	private String mDevUUID;
	private String mConnStatus = "";
	private String mFilePath = "";
	private int mVideoFPS;
	private long mVideoBPS;
	private int mOnlineNm;
	private int mFrameCount;
	private int mIncompleteFrameCount;
	private int mVideoWidth;
	private int mVideoHeight;
	private int mMiniVideoWidth;
	private int mMiniVideoHeight;
	private int mSelectedChannel;

	private int mIncressSize = 500;

	private LinearLayout linPnlCameraInfo;
	private LinearLayout mInfoLayout;
	private LinearLayout mSnapshotLayout;
	private LinearLayout mAlbumLayout;
	private LinearLayout mAudioLayout;
	private LinearLayout mLocalRecordLayout;
	private TextView txtConnectionSlash;
	private TextView txtResolutionSlash;
	private TextView txtShowFPS;
	private TextView txtFPSSlash;
	private TextView txtShowBPS;
	private TextView txtShowOnlineNumber;
	private TextView txtOnlineNumberSlash;
	private TextView txtShowFrameRatio;
	private TextView txtFrameCountSlash;
	private TextView txtQuality;
	private TextView txtRecvFrmPreSec;
	private TextView txtRecvFrmSlash;
	private TextView txtDispFrmPreSeco;
	private TextView txtAudio;

	private TextView txtConnectionStatus;
	private TextView txtConnectionMode;
	private TextView txtResolution;
	private TextView txtFrameRate;
	private TextView txtBitRate;
	private TextView txtOnlineNumber;
	private TextView txtFrameCount;
	private TextView txtIncompleteFrameCount;
	private TextView txtPerformance;

	private boolean mIsListening = false;
	private boolean mIsSpeaking = false;
	private boolean mIsSoftwareDecode = false;
	//For CEO Camera used, P2PCamLive didn't implement local recording
	private boolean mIsRecording = false;
	private boolean mIsHardwareDecodeFailed = false;

	private BitmapDrawable bg;
	private BitmapDrawable bgSplit;

	private ImageButton CH_button;
	private RelativeLayout mSoftMonitorLayout;
	private LinearLayout mHardMonitorLayout;
	private Context mContext;

	private static boolean wait_receive = true;
	private static boolean Watch_album = false;
	private boolean unavailable = false;
	private boolean mSoftCodecDefault = false;
	private boolean mSoftCodecCurrent = false;
	private boolean mIsPortrait = true;

//	private int mActionBarHeight;
	private Bitmap mBitmap;
	
	enum FrameMode {
	    PORTRAIT, LANDSCAPE_ROW_MAJOR, LANDSCAPE_COL_MAJOR
	} 
	private FrameMode mFrameMode = FrameMode.PORTRAIT;

	@SuppressWarnings("deprecation")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		// setContentView(R.layout.live_view_portrait);
		SharedPreferences settings = this.getSharedPreferences("CodecConfig", 0);
		mSoftCodecCurrent = settings.getBoolean("isSoftCodec", false);

		bg = (BitmapDrawable) getResources().getDrawable(R.drawable.bg_striped);
		bgSplit = (BitmapDrawable) getResources().getDrawable(
				R.drawable.bg_striped_split_img);

		Bundle bundle = this.getIntent().getExtras();
		mDevUID = bundle.getString("dev_uid");
		mDevUUID = bundle.getString("dev_uuid");
		mConnStatus = bundle.getString("conn_status");
		mSelectedChannel = bundle.getInt("camera_channel");

		Glog.I("DEBUG", "START :" + mDevUID);

		for (MyCamera camera : MainActivity.CameraList) {

			if (mDevUID.equalsIgnoreCase(camera.getUID())
					&& mDevUUID.equalsIgnoreCase(camera.getUUID())) {
				mCamera = camera;
				break;
			}
		}

		for (DeviceInfo dev : MainActivity.DeviceList) {

			if (mDevUID.equalsIgnoreCase(dev.UID)
					&& mDevUUID.equalsIgnoreCase(dev.UUID)) {
				mDevice = dev;
				break;
			}
		}

		if (mCamera != null) {

			mCamera.registerIOTCListener(this);
			mCamera.SetCameraListener(this);

			if (!mCamera.isSessionConnected()) {

				mCamera.connect(mDevUID);
				mCamera.start(Camera.DEFAULT_AV_CHANNEL, mDevice.View_Account,
						mDevice.View_Password);
				mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
						AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GETSUPPORTSTREAM_REQ,
						SMsgAVIoctrlGetSupportStreamReq.parseContent());
				mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
						AVIOCTRLDEFs.IOTYPE_USER_IPCAM_DEVINFO_REQ,
						AVIOCTRLDEFs.SMsgAVIoctrlDeviceInfoReq.parseContent());
				mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
						AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GETAUDIOOUTFORMAT_REQ,
						AVIOCTRLDEFs.SMsgAVIoctrlGetAudioOutFormatReq
								.parseContent());
				mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
						AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GET_TIMEZONE_REQ,
						AVIOCTRLDEFs.SMsgAVIoctrlTimeZone.parseContent());

			}

		}

		// Inflate the custom view
		final View audioView = LayoutInflater.from(this).inflate(
				R.layout.two_way_audio, null);

		// Bind to its state change
		((RadioGroup) audioView.findViewById(R.id.radioAudio))
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {
					@Override
					public void onCheckedChanged(RadioGroup group, int checkedId) {

						if (checkedId == audioView.findViewById(
								R.id.radioSpeaker).getId()) {

							if (mCamera.isChannelConnected(mSelectedChannel)) {
								mCamera.startSpeaking(mSelectedChannel);
								mIsListening = true;
								mCamera.startListening(mSelectedChannel, mIsListening);
								
							}

						} else if (checkedId == audioView.findViewById(
								R.id.radioMicrophone).getId()) {

							if (mCamera.isChannelConnected(mSelectedChannel)) {
								mCamera.stopListening(mSelectedChannel);
								mCamera.startSpeaking(mSelectedChannel);
								mIsListening = false;
								mIsSpeaking = true;
							}
						}
					}
				});
	}

	@Override
	protected void onStart() {
		super.onStart();
		// FlurryAgent.onStartSession(this, "Q1SDXDZQ21BQMVUVJ16W");
	}

	@Override
	protected void onStop() {
		super.onStop();
		// FlurryAgent.onEndSession(this);
		// Watch_album = true;
	}

	@Override
	protected void onPause() {
		super.onPause();

		if (mSoftMonitor != null)
			mSoftMonitor.deattachCamera();
		if (mHardMonitor != null)
			mHardMonitor.deattachCamera();
		
		if (mCamera != null) {
			mCamera.unregisterIOTCListener(this);
			mCamera.stopSpeaking(mSelectedChannel);
			mCamera.stopListening(mSelectedChannel);
			mCamera.stopShow(mSelectedChannel);
		}

	}

	@Override
	protected void onResume() {
		super.onResume();

		if (mCamera != null) {
			mCamera.registerIOTCListener(this);

			mCamera.startShow(mSelectedChannel, true, mSoftCodecCurrent);

			if (mIsListening)
				mCamera.startListening(mSelectedChannel, mIsListening);
			if (mIsSpeaking)
				mCamera.startSpeaking(mSelectedChannel);
		}

		
		Configuration cfg = getResources().getConfiguration();

		if (cfg.orientation == Configuration.ORIENTATION_PORTRAIT) {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					setupPortraitView(mSoftCodecCurrent);
				}
			});
		} else if (cfg.orientation == Configuration.ORIENTATION_LANDSCAPE) {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					setupLandscapeView(mSoftCodecCurrent);
				}
			});
		}
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		
		if (mSoftMonitor != null)
			mSoftMonitor.deattachCamera();
		if (mHardMonitor != null)
			mHardMonitor.deattachCamera();

		Configuration cfg = getResources().getConfiguration();

		if (cfg.orientation == Configuration.ORIENTATION_LANDSCAPE) {
			if (unavailable)
				setupLandscapeView(true);
			else
				setupLandscapeView(mSoftCodecCurrent);

		} else if (cfg.orientation == Configuration.ORIENTATION_PORTRAIT) {
			if (unavailable)
				setupPortraitView(true);
			else
				setupPortraitView(mSoftCodecCurrent);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == REQUEST_CODE_ALBUM) {
			if(mSoftCodecCurrent) {
				mSoftMonitor = (IMonitor) findViewById(R.id.softMonitor);
				mSoftMonitor.setMaxZoom(3.0f);
				mSoftMonitor.enableDither(mCamera.mEnableDither);
				mSoftMonitor.attachCamera(mCamera, mSelectedChannel);
			}
			else {
				mHardMonitor = (IMonitor) findViewById(R.id.hardMonitor);
				mHardMonitor.setMaxZoom(3.0f);
				mHardMonitor.enableDither(mCamera.mEnableDither);
				mHardMonitor.attachCamera(mCamera, mSelectedChannel);
			}
		}
	}

	private void setupLandscapeView(final boolean runSoftwareDecode) {

		mIsPortrait = false;

		getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getWindow().clearFlags(
				WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);

		
		setContentView(R.layout.live_view_landscape);

		updateAudioStatus();
		
		mSoftCodecCurrent = false;
		if (runSoftwareDecode)
			mSoftCodecCurrent = true;

		
		if (Build.VERSION.SDK_INT < BUILD_VERSION_CODES_ICE_CREAM_SANDWICH) {

			bg.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
			getSupportActionBar().setBackgroundDrawable(bg);

			bgSplit.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
			getSupportActionBar().setSplitBackgroundDrawable(bgSplit);
		}
		
		if (mCamera != null && mCamera.getMultiStreamSupported(0)
				&& mCamera.getSupportedStream().length > 1)
			getSupportActionBar().setSubtitle(
					getText(R.string.dialog_LiveView).toString() + " : "
							+ mDevice.NickName + " - CH"
							+ (mSelectedChannel + 1));
		else
			getSupportActionBar().setSubtitle(
					getText(R.string.dialog_LiveView).toString() + " : "
							+ mDevice.NickName);
		
		
		txtConnectionStatus = null;
		txtConnectionMode = null;
		txtResolution = null;
		txtFrameRate = null;
		txtBitRate = null;
		txtOnlineNumber = null;
		txtFrameCount = null;
		txtIncompleteFrameCount = null;
		txtRecvFrmPreSec = null;
		txtDispFrmPreSeco = null;
		txtPerformance = null;
		
		mSoftMonitorLayout = (RelativeLayout) findViewById(R.id.softMonitorLayout);
		mHardMonitorLayout = (LinearLayout) findViewById(R.id.hardMonitorLayout);
		
		if (!runSoftwareDecode) {
			
			mHardMonitor = (IMonitor) findViewById(R.id.hardMonitor);
			mHardMonitor.setMaxZoom(3.0f);
			mHardMonitor.enableDither(mCamera.mEnableDither);
			mHardMonitor.attachCamera(mCamera, mSelectedChannel);
			
			mSoftMonitorLayout.setVisibility(View.GONE);
			mHardMonitorLayout.setVisibility(View.VISIBLE);
//			mHardMonitor.SetOnMonitorClickListener(this);
			
			mHardMonitor.cleanFrameQueue();
			mHardMonitor.setMediaCodecListener(this);

			// calculate surface view size
			Display display = getWindowManager().getDefaultDisplay();
			Point size = new Point();
			display.getSize(size);
			int width = size.x;
			int height = size.y;

			final SurfaceView surfaceView = (SurfaceView) mHardMonitor;
			surfaceView.getLayoutParams().width = width;
			surfaceView.getLayoutParams().height = height;
			mMiniVideoHeight = surfaceView.getLayoutParams().height;
			mMiniVideoWidth = surfaceView.getLayoutParams().width;
			surfaceView.setLayoutParams(surfaceView.getLayoutParams());
		}
		else {
			
			mSoftMonitor = (IMonitor) findViewById(R.id.softMonitor);
			mSoftMonitor.setMaxZoom(3.0f);
			mSoftMonitor.enableDither(mCamera.mEnableDither);
			mSoftMonitor.attachCamera(mCamera, mSelectedChannel);
//			mSoftMonitor.SetOnMonitorClickListener(this);
			
			mSoftMonitorLayout.setVisibility(View.VISIBLE);
			mHardMonitorLayout.setVisibility(View.GONE);
		}

		
		reScaleMonitor();

	}

	private void setupPortraitView(final boolean runSoftwareDecode) {

		mIsPortrait = true;

		getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getWindow().clearFlags(
				WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);


		setContentView(R.layout.live_view_portrait);

		updateAudioStatus();
		
		mSoftCodecCurrent = false;
		if (runSoftwareDecode)
			mSoftCodecCurrent = true;
		
		

		if (Build.VERSION.SDK_INT < BUILD_VERSION_CODES_ICE_CREAM_SANDWICH) {
			bg.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
			getSupportActionBar().setBackgroundDrawable(bg);

			bgSplit.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
			getSupportActionBar().setSplitBackgroundDrawable(bgSplit);
		}

		if (mCamera != null && mCamera.getMultiStreamSupported(0)
				&& mCamera.getSupportedStream().length > 1)
			getSupportActionBar().setSubtitle(
					getText(R.string.dialog_LiveView).toString() + " : "
							+ mDevice.NickName + " - CH"
							+ (mSelectedChannel + 1));
		else
			getSupportActionBar().setSubtitle(
					getText(R.string.dialog_LiveView).toString() + " : "
							+ mDevice.NickName);

		linPnlCameraInfo = (LinearLayout) findViewById(R.id.pnlCameraInfo);
		mInfoLayout = (LinearLayout) findViewById(R.id.infoLayout);
		mSnapshotLayout = (LinearLayout) findViewById(R.id.layoutSnapshot);
		mAlbumLayout = (LinearLayout) findViewById(R.id.layoutAlbum);
		mAudioLayout = (LinearLayout) findViewById(R.id.layoutAudio);
		mLocalRecordLayout = (LinearLayout) findViewById(R.id.layoutLocalRecord);
		txtConnectionSlash = (TextView) findViewById(R.id.txtConnectionSlash);
		txtResolutionSlash = (TextView) findViewById(R.id.txtResolutionSlash);
		txtShowFPS = (TextView) findViewById(R.id.txtShowFPS);
		txtFPSSlash = (TextView) findViewById(R.id.txtFPSSlash);
		txtShowBPS = (TextView) findViewById(R.id.txtShowBPS);
		txtShowOnlineNumber = (TextView) findViewById(R.id.txtShowOnlineNumber);
		txtOnlineNumberSlash = (TextView) findViewById(R.id.txtOnlineNumberSlash);
		txtShowFrameRatio = (TextView) findViewById(R.id.txtShowFrameRatio);
		txtFrameCountSlash = (TextView) findViewById(R.id.txtFrameCountSlash);
		txtQuality = (TextView) findViewById(R.id.txtQuality);
		txtDispFrmPreSeco = (TextView) findViewById(R.id.txtDispFrmPreSeco);
		txtRecvFrmSlash = (TextView) findViewById(R.id.txtRecvFrmSlash);
		txtRecvFrmPreSec = (TextView) findViewById(R.id.txtRecvFrmPreSec);
		txtPerformance = (TextView) findViewById(R.id.txtPerformance);
		txtAudio = (TextView) findViewById(R.id.txtAudio);

		txtConnectionStatus = (TextView) findViewById(R.id.txtConnectionStatus);
		txtConnectionMode = (TextView) findViewById(R.id.txtConnectionMode);
		txtResolution = (TextView) findViewById(R.id.txtResolution);
		txtFrameRate = (TextView) findViewById(R.id.txtFrameRate);
		txtBitRate = (TextView) findViewById(R.id.txtBitRate);
		txtOnlineNumber = (TextView) findViewById(R.id.txtOnlineNumber);
		txtFrameCount = (TextView) findViewById(R.id.txtFrameCount);
		txtIncompleteFrameCount = (TextView) findViewById(R.id.txtIncompleteFrameCount);

		mSoftMonitorLayout = (RelativeLayout) findViewById(R.id.softMonitorLayout);
		mHardMonitorLayout = (LinearLayout)findViewById(R.id.hardMonitorLayout);
		
		CH_button = (ImageButton) findViewById(R.id.CH_button);
		if (CH_button != null) {
			if (mCamera != null && mCamera.isSessionConnected()
					&& mCamera.getMultiStreamSupported(0)
					&& mCamera.getSupportedStream().length > 1) {
				CH_button.setVisibility(View.VISIBLE);
			} else {
				CH_button.setVisibility(View.GONE);
			}
		}

		mSnapshotLayout.setOnTouchListener( layoutOnTouchListener );
		mAlbumLayout.setOnTouchListener( layoutOnTouchListener );
		mAudioLayout.setOnTouchListener( layoutOnTouchListener );
		mLocalRecordLayout.setOnTouchListener( layoutOnTouchListener );

		if(DEBUG_REC)
		{
			mLocalRecordLayout.setVisibility(View.VISIBLE);
		}

		txtConnectionStatus.setText(mConnStatus);
		txtConnectionSlash.setText("");
		txtResolutionSlash.setText("");

		txtResolution.setText("0" + "x" + "0 ");
		txtShowFPS.setText("");
		txtFPSSlash.setText("");
		txtShowBPS.setText("");
		txtOnlineNumberSlash.setText("");
		txtShowFrameRatio.setText("");
		txtFrameCountSlash.setText("");
		txtRecvFrmSlash.setText("");
		txtPerformance
				.setText(getPerformance((int) (((float) mCamera
						.getDispFrmPreSec() / (float) mCamera
						.getRecvFrmPreSec()) * 100)));

		txtConnectionMode.setVisibility(View.GONE);
		txtFrameRate.setVisibility(View.GONE);
		txtBitRate.setVisibility(View.GONE);
		txtFrameCount.setVisibility(View.GONE);
		txtIncompleteFrameCount.setVisibility(View.GONE);
		txtRecvFrmPreSec.setVisibility(View.GONE);
		txtDispFrmPreSeco.setVisibility(View.GONE);

		linPnlCameraInfo.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View arg0) {

				MainActivity.nShowMessageCount++;
				showMessage();

			}
		});

		CH_button.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View arg0) {

				final AlertDialog dlg = new AlertDialog.Builder(
						LiveViewActivity.this).create();
				ListView view = new ListView(LiveViewActivity.this);
				dlg.setView(view);
				dlg.setCanceledOnTouchOutside(true);
				Window window = dlg.getWindow();
				WindowManager.LayoutParams lp = window.getAttributes();
				// lp.y = -64;
				lp.dimAmount = 0f;

				ArrayAdapter<SStreamDef> adapter = new ArrayAdapter<SStreamDef>(
						LiveViewActivity.this,
						android.R.layout.simple_list_item_1);
				for (SStreamDef streamDef : mCamera.getSupportedStream())
					adapter.add(streamDef);

				view.setAdapter(adapter);
				view.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {

						if(mSoftMonitor != null)
							mSoftMonitor.deattachCamera();
						if(mHardMonitor != null)
							mHardMonitor.deattachCamera();

						mCamera.stopShow(mSelectedChannel);
						mCamera.stopListening(mSelectedChannel);
						mCamera.stopSpeaking(mSelectedChannel);

						try {
							Thread.sleep(500);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						System.out.println("OnSpinStreamItemSelected: " + arg2);
						mSelectedChannel = arg2;

						if (mCamera != null
								&& mCamera.getMultiStreamSupported(0)
								&& mCamera.getSupportedStream().length > 1)
							getSupportActionBar().setSubtitle(
									getText(R.string.dialog_LiveView)
											.toString()
											+ " : "
											+ mDevice.NickName
											+ " - CH"
											+ (mSelectedChannel + 1));
						else
							getSupportActionBar().setSubtitle(
									getText(R.string.dialog_LiveView)
											.toString()
											+ " : "
											+ mDevice.NickName);

						DisplayMetrics metrics = new DisplayMetrics();
						getWindowManager().getDefaultDisplay().getMetrics(
								metrics);
						Log.i("IOTCamViewer", "" + metrics.widthPixels + " X "
								+ metrics.heightPixels);
//						if (metrics.widthPixels < metrics.heightPixels)
//							setupViewInPortraitLayout();
//						else
//							setupViewInLandscapeLayout();

						if(mSoftCodecDefault){
							mSoftMonitor.enableDither(mCamera.mEnableDither);
							mSoftMonitor.attachCamera(mCamera, mSelectedChannel);
						}
						else {
							mHardMonitor.enableDither(mCamera.mEnableDither);
							mHardMonitor.attachCamera(mCamera, mSelectedChannel);
						}
						Glog.D("www", "CH_button_startShow");

						if (mIsListening)
							mCamera.startListening(mSelectedChannel, mIsListening);
						if (mIsSpeaking)
							mCamera.startSpeaking(mSelectedChannel);

						handler.postDelayed(new Runnable() {
							@Override
							public void run() {
								mCamera.startShow(mSelectedChannel, true, mSoftCodecDefault);
//								CH_button.setText("CH" + (mSelectedChannel + 1));
							}
						}, 500);

						// DisplayMetrics metrics = new DisplayMetrics();
						// getWindowManager().getDefaultDisplay().getMetrics(metrics);
						// Log.i("IOTCamViewer", "" + metrics.widthPixels +
						// " X "
						// + metrics.heightPixels);
						// if (metrics.widthPixels < metrics.heightPixels)
						// setupViewInPortraitLayout();
						// else
						// setupViewInLandscapeLayout();

						dlg.dismiss();
					}
				});

				dlg.show();

			}
		});



		if (!runSoftwareDecode) {

			mHardMonitor = (IMonitor) findViewById(R.id.hardMonitor);
			mHardMonitor.setMaxZoom(3.0f);
			mHardMonitor.enableDither(mCamera.mEnableDither);
			mHardMonitor.attachCamera(mCamera, mSelectedChannel);

			mSoftMonitorLayout.setVisibility(View.GONE);
			mHardMonitorLayout.setVisibility(View.VISIBLE);

			mHardMonitor.cleanFrameQueue();
			mHardMonitor.setMediaCodecListener(this);


			// calculate surface view size
			Display display = getWindowManager().getDefaultDisplay();
			Point size = new Point();
			display.getSize(size);
			int width = size.x;
			int height = size.y;

			final SurfaceView surfaceView = (SurfaceView) mHardMonitor;
			surfaceView.getLayoutParams().width = width;
			handler.post(new Runnable() {
				@Override
				public void run() {
					if (mHardMonitorLayout.getMeasuredHeight() == 0) {
						handler.postDelayed(this, 200);
					} else {
						surfaceView.getLayoutParams().height = mHardMonitorLayout.getMeasuredHeight();
						mMiniVideoHeight = surfaceView.getLayoutParams().height;
						mMiniVideoWidth = surfaceView.getLayoutParams().width;
						surfaceView.setLayoutParams(surfaceView.getLayoutParams());
					}
				}
			});
		}
		else{
			mSoftMonitor = (IMonitor) findViewById(R.id.softMonitor);
			mSoftMonitor.setMaxZoom(3.0f);
			mSoftMonitor.enableDither(mCamera.mEnableDither);
			mSoftMonitor.attachCamera(mCamera, mSelectedChannel);

			mSoftMonitorLayout.setVisibility(View.VISIBLE);
			mHardMonitorLayout.setVisibility(View.GONE);
		}


		reScaleMonitor();

		// calculate surface view size

//		showMessage();


	}

	private Toast mAlbumToast;
	private Toast mSnapshotToast;
	private boolean mIsLongPressed;
	private Runnable mAlbumLongPressed = new Runnable() {
		public void run() {
			if(mAlbumToast == null) {
				mAlbumToast = Toast.makeText(LiveViewActivity.this, R.string.tips_btn_album, Toast.LENGTH_SHORT);
			}
			mAlbumToast.show();
			mIsLongPressed = true;
		}
	};

	private Runnable mSnapshotLongPressed = new Runnable() {
		public void run() {
			if(mSnapshotToast == null) {
				mSnapshotToast = Toast.makeText(LiveViewActivity.this, R.string.tips_btn_snapshot, Toast.LENGTH_SHORT);
			}
			mSnapshotToast.show();
			mIsLongPressed = true;
		}
	};

	private View.OnTouchListener layoutOnTouchListener = new View.OnTouchListener() {
		@Override
		public boolean onTouch(View view, MotionEvent motionEvent) {
			switch (motionEvent.getAction())
			{
				case MotionEvent.ACTION_DOWN:
				{
					switch(view.getId())
					{
						case R.id.layoutAlbum:
						{
							handler.postDelayed(mAlbumLongPressed, 500);
							break;
						}
						case R.id.layoutSnapshot:
						{
							handler.postDelayed(mSnapshotLongPressed, 500);
							break;
						}
					}
					view.setBackgroundColor(0xff4d5459);
					return true;
				}

				case MotionEvent.ACTION_UP:
				case MotionEvent.ACTION_CANCEL:
				{
					switch(view.getId())
					{
						case R.id.layoutAlbum:
						{
							if(mAlbumToast != null)
							{
								mAlbumToast.cancel();
							}
							handler.removeCallbacks(mAlbumLongPressed);
							break;
						}
						case R.id.layoutSnapshot:
						{
							if(mSnapshotToast != null)
							{
								mSnapshotToast.cancel();
							}
							handler.removeCallbacks(mSnapshotLongPressed);
							break;
						}
					}
					view.setBackgroundColor(0xff252c33);

					if((motionEvent.getAction() == MotionEvent.ACTION_UP ) && !mIsLongPressed)
					{
						handleTouchEvent(view.getId());
						return true;
					}
					mIsLongPressed = false;
					return false;
				}

			}
			return false;
		}
	};

	private void handleTouchEvent( int id )
	{

		switch(id)
		{
			case R.id.layoutAlbum:
		 	{

				// if (monitor != null) {
				// monitor.deattachCamera();
				// }

				Watch_album = true;

				File folder = new File(Environment.getExternalStorageDirectory()
						.getAbsolutePath() + "/Snapshot/" + mDevUID);
				// File folder = new
				// File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath()
				// + "/Snapshot");
				String[] allFiles = folder.list();

				if (allFiles != null && allFiles.length > 0)
				{

					if(mSoftMonitor != null)
						mSoftMonitor.deattachCamera();
					if(mHardMonitor != null)
						mHardMonitor.deattachCamera();

					String file = folder.getAbsolutePath() + "/"
							+ allFiles[allFiles.length - 1];

					/*
					 * MediaScannerConnection.scanFile(LiveViewActivity.this, new
					 * String[] { file.toString() }, new String[] {"image/*"}, new
					 * MediaScannerConnection.OnScanCompletedListener() { public
					 * void onScanCompleted(String path, Uri uri) {
					 * Glog.I("ExternalStorage", "Scanned " + path + ":");
					 * Glog.I("ExternalStorage", "-> uri=" + uri);
					 *
					 * Intent intent = new Intent(Intent.ACTION_VIEW); //
					 * intent.addCategory(Intent.CATEGORY_OPENABLE); //
					 * intent.setType("image/*"); intent.setDataAndType(uri,
					 * "image/*"); startActivity(intent); } });
					 */

					/*
					 * Intent intent = new Intent(Intent.ACTION_VIEW); Uri
					 * hacked_uri = Uri.parse("file://" +
					 * Uri.parse(file).getPath()); intent.setDataAndType(hacked_uri,
					 * "image/*"); startActivity(intent);
					 */

					Intent intent = new Intent(LiveViewActivity.this,
							GridViewGalleryActivity.class);
					intent.putExtra("snap", mDevUID);
					intent.putExtra("images_path", folder.getAbsolutePath());
					startActivity(intent);

				}
				else
				{
					String msg = LiveViewActivity.this.getText(
							R.string.tips_no_snapshot_found).toString();
					Toast.makeText(LiveViewActivity.this, msg, Toast.LENGTH_SHORT)
							.show();
				}
				break;
			}

			case R.id.layoutSnapshot:
			{

				if (mCamera != null && mCamera.isChannelConnected(mSelectedChannel))
				{

					if (isSDCardValid())
					{

						File rootFolder = new File(Environment
								.getExternalStorageDirectory().getAbsolutePath()
								+ "/Snapshot/");
						File targetFolder = new File(rootFolder.getAbsolutePath()
								+ "/" + mDevUID);
						// File rootFolder = new
						// File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath()
						// + "/Snapshot");
						// File targetFolder = new
						// File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath()
						// + "/Snapshot");

						if (!rootFolder.exists()) {
							try {
								rootFolder.mkdir();
							} catch (SecurityException se) {
								Glog.D("DEBUG","Make Dir ERROR: " + rootFolder.getPath());
							}
						}

						if (!targetFolder.exists()) {

							try {
								targetFolder.mkdir();
							} catch (SecurityException se) {
								Glog.D("DEBUG","Make Dir ERROR: " + targetFolder.getPath());
							}
						}

						final String file = targetFolder.getAbsoluteFile() + "/"
								+ getFileNameWithTime();
						// Bitmap frame = mCamera != null ?
						// mCamera.Snapshot(mSelectedChannel) : null;
						mFilePath = file;


						// if (frame != null && saveImage(file, frame) /* &&
						// db.addSnapshot(mDevUID, fileName,
						// System.currentTimeMillis()) >= 0 */) {
						//
						// //sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
						// Uri.parse("file://" +
						// Environment.getExternalStorageDirectory())));
						//
						// MediaScannerConnection.scanFile(this,
						// new String[] { file.toString() },
						// new String[] {"image/*"},
						// new MediaScannerConnection.OnScanCompletedListener() {
						// public void onScanCompleted(String path, Uri uri) {
						// Glog.I("ExternalStorage", "Scanned " + path + ":");
						// Glog.I("ExternalStorage", "-> uri=" + uri);
						// Message msg = handler.obtainMessage();
						// msg.what = STS_SNAPSHOT_SCANED;
						// handler.sendMessage(msg);
						// }
						// });
						//
						// }
						if (mCamera != null)
						{
							mCamera.setSnapshot(mContext, file);
						}
						else
						{

							Toast.makeText(LiveViewActivity.this,
									getText(R.string.tips_snapshot_failed),
									Toast.LENGTH_SHORT).show();
						}

					}
					else
					{

						Toast.makeText(
								LiveViewActivity.this,
								LiveViewActivity.this.getText(
										R.string.tips_no_sdcard).toString(),
								Toast.LENGTH_SHORT).show();
					}
				}
				break;
			}
			case R.id.layoutAudio:
			{

				ArrayList<String> s = new ArrayList<String>();
				s.add(getText(R.string.txtMute).toString());
				if (mCamera.getAudioInSupported(0))
					s.add(getText(R.string.txtListen).toString());
				if (mCamera.getAudioOutSupported(0))
					s.add(getText(R.string.txtSpeak).toString());

				ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
						android.R.layout.simple_list_item_1, s);

				final AlertDialog dlg = new AlertDialog.Builder(this).create();
				dlg.setTitle(null);
				dlg.setIcon(null);

				ListView view = new ListView(this);
				view.setAdapter(adapter);
				view.setOnItemClickListener(new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> arg0, View view,
											int position, long id) {

						if (mCamera == null)
							return;

						if (position == 1) { // Listening
							mIsListening = true;
							mIsSpeaking = false;
							mCamera.stopSpeaking(mSelectedChannel);
							mCamera.startListening(mSelectedChannel, mIsListening);

						} else if (position == 2) { // Speaking
							mIsListening = false;
							mIsSpeaking = true;
							mCamera.stopListening(mSelectedChannel);
							mCamera.startSpeaking(mSelectedChannel);

						} else if (position == 0) { // Mute
							mCamera.stopListening(mSelectedChannel);
							mCamera.stopSpeaking(mSelectedChannel);
							mIsListening = mIsSpeaking = false;
						}

						dlg.dismiss();
						updateAudioStatus();
					}
				});

				dlg.setView(view);
				dlg.setCanceledOnTouchOutside(true);
				dlg.show();
				break;
			}
			case R.id.layoutLocalRecord:
			{
				if(mIsRecording==false)
				{
					mIsRecording=true;
					Toast.makeText(this, "Start local recording", Toast.LENGTH_LONG).show();
					mCamera.startListening(0, true);
					mCamera.startRecording("/sdcard/text2.mp4");
				}
				else
				{
					mIsRecording=false;
					Toast.makeText(this, "stop local recording", Toast.LENGTH_LONG).show();
					mCamera.stopListening(0);
					mCamera.stopRecording();

				}
				break;
			}

		}
	}

	private void updateAudioStatus()
	{
		if( txtAudio != null )
		{
			// Add Audio Control Menu
			if (!mIsListening && !mIsSpeaking)
				txtAudio.setText(Html.fromHtml("<b>" + getText(R.string.txtMute) + "</b>"));
			else if (mIsListening && !mIsSpeaking)
				txtAudio.setText(Html.fromHtml("<b>" + getText(R.string.txtListening) + "</b>"));
			else if (!mIsListening && mIsSpeaking)
				txtAudio.setText(Html.fromHtml("<b>" + getText(R.string.txtSpeaking) + "</b>"));
		}

		LiveViewActivity.this.invalidateOptionsMenu();

	}

	private void showMessage() {

		St_SInfo stSInfo = new St_SInfo();
		IOTCAPIs.IOTC_Session_Check(mCamera.getMSID(), stSInfo);

		if (MainActivity.nShowMessageCount >= 10) {

			txtConnectionStatus.setText(mConnStatus);
			txtConnectionMode.setText(getSessionMode(mCamera != null ? mCamera
					.getSessionMode() : -1)
					+ " C: "
					+ IOTCAPIs.IOTC_Get_Nat_Type()
					+ ", D: "
					+ stSInfo.NatType
					+ ",R" + mCamera.getbResend());

			txtConnectionSlash.setText(" / ");
			txtResolutionSlash.setText(" / ");
			txtShowFPS.setText(getText(R.string.txtFPS));
			txtFPSSlash.setText(" / ");
			txtShowBPS.setText(getText(R.string.txtBPS));
			// txtShowOnlineNumber.setText(getText(R.string.txtOnlineNumber));
			txtOnlineNumberSlash.setText(" / ");
			txtShowFrameRatio.setText(getText(R.string.txtFrameRatio));
			txtFrameCountSlash.setText(" / ");
			txtQuality.setText(getText(R.string.txtQuality));
			txtRecvFrmSlash.setText(" / ");
			// mCamera.getDispFrmPreSec()
			txtConnectionMode.setVisibility(View.VISIBLE);
			txtResolution.setVisibility(View.VISIBLE);
			txtFrameRate.setVisibility(View.VISIBLE);
			txtBitRate.setVisibility(View.VISIBLE);
			txtOnlineNumber.setVisibility(View.VISIBLE);
			txtFrameCount.setVisibility(View.VISIBLE);
			txtIncompleteFrameCount.setVisibility(View.VISIBLE);
			txtRecvFrmPreSec.setVisibility(View.VISIBLE);
			txtDispFrmPreSeco.setVisibility(View.VISIBLE);
		}
	}

	private void addImageGallery(File file) {
		ContentValues values = new ContentValues();
		values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
		values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); // setar
																		// isso
		getContentResolver().insert(
				MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
	}

	private boolean saveImage(String fileName, Bitmap frame) {

		if (fileName == null || fileName.length() <= 0)
			return false;

		boolean bErr = false;
		FileOutputStream fos = null;

		try {

			fos = new FileOutputStream(fileName, false);
			frame.compress(Bitmap.CompressFormat.JPEG, 90, fos);
			fos.flush();
			fos.close();

		} catch (Exception e) {

			bErr = true;
			System.out.println("saveImage(.): " + e.getMessage());

		} finally {

			if (bErr) {

				if (fos != null) {
					try {
						fos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				return false;
			}
		}

		addImageGallery(new File(fileName));
		return true;
	}

	// filename: such as,M20101023_181010.jpg
	private static String getFileNameWithTime() {

		Calendar c = Calendar.getInstance();
		int mYear = c.get(Calendar.YEAR);
		int mMonth = c.get(Calendar.MONTH) + 1;
		int mDay = c.get(Calendar.DAY_OF_MONTH);
		int mHour = c.get(Calendar.HOUR_OF_DAY);
		int mMinute = c.get(Calendar.MINUTE);
		int mSec = c.get(Calendar.SECOND);
		int mMilliSec = c.get(Calendar.MILLISECOND);

		StringBuffer sb = new StringBuffer();
		sb.append("IMG_");
		sb.append(mYear);
		if (mMonth < 10)
			sb.append('0');
		sb.append(mMonth);
		if (mDay < 10)
			sb.append('0');
		sb.append(mDay);
		sb.append('_');
		if (mHour < 10)
			sb.append('0');
		sb.append(mHour);
		if (mMinute < 10)
			sb.append('0');
		sb.append(mMinute);
		if (mSec < 10)
			sb.append('0');
		sb.append(mSec);
		sb.append(".jpg");

		return sb.toString();
	}

	private String getSessionMode(int mode) {

		String result = "";
		if (mode == 0)
			result = getText(R.string.connmode_p2p).toString();
		else if (mode == 1)
			result = getText(R.string.connmode_relay).toString();
		else if (mode == 2)
			result = getText(R.string.connmode_lan).toString();
		else
			result = getText(R.string.connmode_none).toString();

		return result;
	}

	private String getPerformance(int mode) {

		String result = "";
		if (mode < 30)
			result = getText(R.string.txtBad).toString();
		else if (mode < 60)
			result = getText(R.string.txtNormal).toString();
		else
			result = getText(R.string.txtGood).toString();

		return result;
	}

	private static boolean isSDCardValid() {

		return Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED);
	}

	private void quit() {
	/* return values to main page */
		Bundle extras = new Bundle();
		extras.putString("dev_uuid", mDevUUID);
		extras.putString("dev_uid", mDevUID);
		extras.putInt("camera_channel", mSelectedChannel);
		Bitmap bmp;
		byte[] snapshot = null;

		if (mBitmap!=null) {
			bmp = compressImage(mBitmap);
			if (bmp.getWidth() * bmp.getHeight() > THUMBNAIL_LIMIT_WIDTH
					* THUMBNAIL_LIMIT_HEIGHT) {
				bmp = Bitmap.createScaledBitmap(bmp, THUMBNAIL_LIMIT_WIDTH,
						THUMBNAIL_LIMIT_HEIGHT, false);
			}

			snapshot = DatabaseManager.getByteArrayFromBitmap(bmp);
			bmp.recycle();
		}
		if (snapshot!=null){
			DatabaseManager manager = new DatabaseManager(this);
			manager.updateDeviceChannelByUID(mDevUID, mSelectedChannel);

			manager.updateDeviceSnapshotByUID(mDevUID, snapshot);
			extras.putByteArray("snapshot", snapshot);
		}else{
			bmp = mCamera.Snapshot(mSelectedChannel);
			if (bmp != null) {
				bmp = compressImage(mCamera.Snapshot(mSelectedChannel));

				if(bmp != null) {
					snapshot = DatabaseManager.getByteArrayFromBitmap(bmp);
					bmp.recycle();
				}
			}

			DatabaseManager manager = new DatabaseManager(this);
			manager.updateDeviceChannelByUID(mDevUID, mSelectedChannel);

			if (snapshot != null) {
				manager.updateDeviceSnapshotByUID(mDevUID, snapshot);
				extras.putByteArray("snapshot", snapshot);
			}
		}

		if (mCamera != null) {

			if (mIsListening)
				mCamera.LastAudioMode = 1;
			else if (mIsSpeaking)
				mCamera.LastAudioMode = 2;
			else
				mCamera.LastAudioMode = 0;

		}

		Intent intent = new Intent();
		intent.putExtras(extras);
		setResult(RESULT_OK, intent);
		finish();
	}

	private Bitmap compressImage(Bitmap image) {

		Bitmap tempBitmap = image;

		try {

			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			image.compress(Bitmap.CompressFormat.JPEG, 5, baos);
			ByteArrayInputStream isBm = new ByteArrayInputStream(
					baos.toByteArray());
			Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
			return bitmap;

		} catch (Exception e) {
			e.printStackTrace();
		}

		return tempBitmap;
	}

//	@Override
//	public boolean onCreateOptionsMenu(Menu menu) {
//
//		if( mIsPortrait )
//		{
//			return true;
//		}
//
//		// Add Album Menu
//		menu.add(Menu.NONE, R.id.layoutAlbum, 1, getText(R.string.tips_btn_album))
//				.setIcon(R.drawable.ic_menu_album)
//				.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
//
//		// Add Snapshot Menu
//		menu.add(Menu.NONE, R.id.layoutSnapshot, 2, getText( R.string.tips_btn_snapshot))
//				.setIcon(
//						(mCamera != null
//								&& mCamera.isChannelConnected(mSelectedChannel) ? R.drawable.ic_menu_snapshot
//								: R.drawable.ic_menu_snapshot_inverse))
//				.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
//
//		// Add Sub-Channel Menu
//		// if (mCamera != null && mCamera.isSessionConnected() &&
//		// mCamera.getMultiStreamSupported(0) &&
//		// mCamera.getSupportedStream().length > 1) {
//		// menu.add(Menu.NONE, OPT_MENU_ITEM_SUBSTREAM, 3,
//		// "Ch").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM |
//		// MenuItem.SHOW_AS_ACTION_WITH_TEXT);
//		// }
//
//
//		// Add Audio Control Menu
//		if (!mIsListening && !mIsSpeaking)
//			menu.add(Menu.NONE, R.id.layoutAudio, 3,
//					getText(R.string.txtMute)).setShowAsAction(
//					MenuItem.SHOW_AS_ACTION_IF_ROOM
//							| MenuItem.SHOW_AS_ACTION_WITH_TEXT);
//		else if (mIsListening && !mIsSpeaking)
//			menu.add(Menu.NONE, R.id.layoutAudio, 3,
//					getText(R.string.txtListening)).setShowAsAction(
//					MenuItem.SHOW_AS_ACTION_IF_ROOM
//							| MenuItem.SHOW_AS_ACTION_WITH_TEXT);
//		else if (!mIsListening && mIsSpeaking)
//			menu.add(Menu.NONE, R.id.layoutAudio, 3,
//					getText(R.string.txtSpeaking)).setShowAsAction(
//					MenuItem.SHOW_AS_ACTION_IF_ROOM
//							| MenuItem.SHOW_AS_ACTION_WITH_TEXT);
//
//		if (DEBUG_REC) {
//			menu.add(Menu.NONE, R.id.layoutLocalRecord, 6, "LocalRecord")
//					.setIcon(android.R.drawable.ic_dialog_alert)
//					.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
//		}
//
//		return true;
//	}
//
//	@Override
//	public boolean onOptionsItemSelected(MenuItem item) {
//
//		int id = item.getItemId();
//		handleTouchEvent(id);
////
////		if (id == OPT_MENU_ITEM_ALBUM) {
////
////			// if (monitor != null) {
////			// monitor.deattachCamera();
////			// }
////
////			Watch_album = true;
////
////			File folder = new File(Environment.getExternalStorageDirectory()
////					.getAbsolutePath() + "/Snapshot/" + mDevUID);
////			// File folder = new
////			// File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath()
////			// + "/Snapshot");
////			String[] allFiles = folder.list();
////
////			if (allFiles != null && allFiles.length > 0) {
////
////				if(mSoftMonitor != null)
////					mSoftMonitor.deattachCamera();
////				if(mHardMonitor != null)
////					mHardMonitor.deattachCamera();
////
////				String file = folder.getAbsolutePath() + "/"
////						+ allFiles[allFiles.length - 1];
////
////				/*
////				 * MediaScannerConnection.scanFile(LiveViewActivity.this, new
////				 * String[] { file.toString() }, new String[] {"image/*"}, new
////				 * MediaScannerConnection.OnScanCompletedListener() { public
////				 * void onScanCompleted(String path, Uri uri) {
////				 * Glog.I("ExternalStorage", "Scanned " + path + ":");
////				 * Glog.I("ExternalStorage", "-> uri=" + uri);
////				 *
////				 * Intent intent = new Intent(Intent.ACTION_VIEW); //
////				 * intent.addCategory(Intent.CATEGORY_OPENABLE); //
////				 * intent.setType("image/*"); intent.setDataAndType(uri,
////				 * "image/*"); startActivity(intent); } });
////				 */
////
////				/*
////				 * Intent intent = new Intent(Intent.ACTION_VIEW); Uri
////				 * hacked_uri = Uri.parse("file://" +
////				 * Uri.parse(file).getPath()); intent.setDataAndType(hacked_uri,
////				 * "image/*"); startActivity(intent);
////				 */
////
////				Intent intent = new Intent(LiveViewActivity.this,
////						GridViewGalleryActivity.class);
////				intent.putExtra("snap", mDevUID);
////				intent.putExtra("images_path", folder.getAbsolutePath());
////				startActivity(intent);
////
////			} else {
////				String msg = LiveViewActivity.this.getText(
////						R.string.tips_no_snapshot_found).toString();
////				Toast.makeText(LiveViewActivity.this, msg, Toast.LENGTH_SHORT)
////						.show();
////			}
////
////		} else if (id == OPT_MENU_ITEM_SNAPSHOT) {
////
////			if (mCamera != null && mCamera.isChannelConnected(mSelectedChannel)) {
////
////				if (isSDCardValid()) {
////
////					File rootFolder = new File(Environment
////							.getExternalStorageDirectory().getAbsolutePath()
////							+ "/Snapshot/");
////					File targetFolder = new File(rootFolder.getAbsolutePath()
////							+ "/" + mDevUID);
////					// File rootFolder = new
////					// File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath()
////					// + "/Snapshot");
////					// File targetFolder = new
////					// File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath()
////					// + "/Snapshot");
////
////					if (!rootFolder.exists()) {
////						try {
////							rootFolder.mkdir();
////						} catch (SecurityException se) {
////							super.onOptionsItemSelected(item);
////						}
////					}
////
////					if (!targetFolder.exists()) {
////
////						try {
////							targetFolder.mkdir();
////						} catch (SecurityException se) {
////							super.onOptionsItemSelected(item);
////						}
////					}
////
////					final String file = targetFolder.getAbsoluteFile() + "/"
////							+ getFileNameWithTime();
////					// Bitmap frame = mCamera != null ?
////					// mCamera.Snapshot(mSelectedChannel) : null;
////					mFilePath = file;
////					if (mCamera != null) {
////						mCamera.setSnapshot(mContext, file);
////					}
////
////					// if (frame != null && saveImage(file, frame) /* &&
////					// db.addSnapshot(mDevUID, fileName,
////					// System.currentTimeMillis()) >= 0 */) {
////					//
////					// //sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
////					// Uri.parse("file://" +
////					// Environment.getExternalStorageDirectory())));
////					//
////					// MediaScannerConnection.scanFile(this,
////					// new String[] { file.toString() },
////					// new String[] {"image/*"},
////					// new MediaScannerConnection.OnScanCompletedListener() {
////					// public void onScanCompleted(String path, Uri uri) {
////					// Glog.I("ExternalStorage", "Scanned " + path + ":");
////					// Glog.I("ExternalStorage", "-> uri=" + uri);
////					// Message msg = handler.obtainMessage();
////					// msg.what = STS_SNAPSHOT_SCANED;
////					// handler.sendMessage(msg);
////					// }
////					// });
////					//
////					// }
////
////					else {
////
////						Toast.makeText(LiveViewActivity.this,
////								getText(R.string.tips_snapshot_failed),
////								Toast.LENGTH_SHORT).show();
////					}
////
////				} else {
////
////					Toast.makeText(
////							LiveViewActivity.this,
////							LiveViewActivity.this.getText(
////									R.string.tips_no_sdcard).toString(),
////							Toast.LENGTH_SHORT).show();
////				}
////			}
////
////		} else if (id == OPT_MENU_ITEM_AUDIOCTRL) {
////
////			ArrayList<String> s = new ArrayList<String>();
////			s.add(getText(R.string.txtMute).toString());
////			if (mCamera.getAudioInSupported(0))
////				s.add(getText(R.string.txtListen).toString());
////			if (mCamera.getAudioOutSupported(0))
////				s.add(getText(R.string.txtSpeak).toString());
////
////			ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
////					android.R.layout.simple_list_item_1, s);
////
////			final AlertDialog dlg = new AlertDialog.Builder(this).create();
////			dlg.setTitle(null);
////			dlg.setIcon(null);
////
////			ListView view = new ListView(this);
////			view.setAdapter(adapter);
////			view.setOnItemClickListener(new OnItemClickListener() {
////				@Override
////				public void onItemClick(AdapterView<?> arg0, View view,
////						int position, long id) {
////
////					if (mCamera == null)
////						return;
////
////					if (position == 1) { // Listening
////						mIsListening = true;
////						mIsSpeaking = false;
////						mCamera.stopSpeaking(mSelectedChannel);
////						mCamera.startListening(mSelectedChannel, mIsListening);
////
////					} else if (position == 2) { // Speaking
////						mIsListening = false;
////						mIsSpeaking = true;
////						mCamera.stopListening(mSelectedChannel);
////						mCamera.startSpeaking(mSelectedChannel);
////
////					} else if (position == 0) { // Mute
////						mCamera.stopListening(mSelectedChannel);
////						mCamera.stopSpeaking(mSelectedChannel);
////						mIsListening = mIsSpeaking = false;
////					}
////
////					dlg.dismiss();
////					LiveViewActivity.this.invalidateOptionsMenu();
////				}
////			});
////
////			dlg.setView(view);
////			dlg.setCanceledOnTouchOutside(true);
////			dlg.show();
////
////		} else
//
////		if (id == OPT_MENU_ITEM_AUDIO_IN) {
////
////			if (!mIsListening) {
////				mCamera.startListening(mSelectedChannel, mIsListening);
////			} else {
////				mCamera.stopListening(mSelectedChannel);
////			}
////
////			mIsListening = !mIsListening;
////
////			this.invalidateOptionsMenu();
////
////		} else if (id == OPT_MENU_ITEM_AUDIO_OUT) {
////
////			if (!mIsSpeaking) {
////				mCamera.startSpeaking(mSelectedChannel);
////			} else {
////				mCamera.stopSpeaking(mSelectedChannel);
////			}
////
////			mIsSpeaking = !mIsSpeaking;
////
////			this.invalidateOptionsMenu();
////		}
//
//		return super.onOptionsItemSelected(item);
//	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		switch (keyCode)
		{
			case KeyEvent.KEYCODE_BACK:
			{
				quit();
			}
		}

		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void receiveFrameData(final Camera camera, int avChannel, Bitmap bmp){

		if (mCamera == camera && avChannel == mSelectedChannel){

			if( bmp == null ){
				return;
			}else{
				if ((bmp.getWidth() != mVideoWidth || bmp.getHeight() != mVideoHeight)){
					mVideoWidth = bmp.getWidth();
					mVideoHeight = bmp.getHeight();

					reScaleMonitor();
				}
				if(mBitmap != null && !mBitmap.isRecycled())
					mBitmap.recycle();

				mBitmap=bmp;
			}
		}
	}

	@Override
	public void receiveFrameInfo(final Camera camera, int avChannel,
								 long bitRate, int frameRate, int onlineNm, int frameCount,
								 int incompleteFrameCount) {

		if (mCamera == camera && avChannel == mSelectedChannel) {

			mVideoFPS = frameRate;
			mVideoBPS = bitRate;
			mOnlineNm = onlineNm;
			mFrameCount = frameCount;
			mIncompleteFrameCount = incompleteFrameCount;

			Bundle bundle = new Bundle();
			bundle.putInt("avChannel", avChannel);

			Message msg = handler.obtainMessage();
			msg.what = STS_CHANGE_CHANNEL_STREAMINFO;
			msg.setData(bundle);
			handler.sendMessage(msg);
		}
	}

	@Override
	public void receiveChannelInfo(final Camera camera, int avChannel,
								   int resultCode) {

		if (mCamera == camera && avChannel == mSelectedChannel) {
			Bundle bundle = new Bundle();
			bundle.putInt("avChannel", avChannel);

			Message msg = handler.obtainMessage();
			msg.what = resultCode;
			msg.setData(bundle);
			handler.sendMessage(msg);
		}
	}

	@Override
	public void receiveSessionInfo(final Camera camera, int resultCode) {

		if (mCamera == camera) {
			Bundle bundle = new Bundle();
			Message msg = handler.obtainMessage();
			msg.what = resultCode;
			msg.setData(bundle);
			handler.sendMessage(msg);
		}
	}

	@Override
	public void receiveIOCtrlData(final Camera camera, int avChannel,
								  int avIOCtrlMsgType, byte[] data) {

		if (mCamera == camera) {
			Bundle bundle = new Bundle();
			bundle.putInt("avChannel", avChannel);
			bundle.putByteArray("data", data);
			Message msg = handler.obtainMessage();
			msg.what = avIOCtrlMsgType;
			handler.sendMessage(msg);
		}
	}

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {

			Bundle bundle = msg.getData();
			int avChannel = bundle.getInt("avChannel");

			St_SInfo stSInfo = new St_SInfo();
			IOTCAPIs.IOTC_Session_Check(mCamera.getMSID(), stSInfo);

			switch (msg.what) {

			case STS_CHANGE_CHANNEL_STREAMINFO:

				if (txtResolution != null) {
					txtResolution.setText(String.valueOf(Camera.view_Width)
							+ "x" + String.valueOf(Camera.view_Height));
				}

				if (txtFrameRate != null) {
					// txtFrameRate.setText(String.valueOf(mVideoFPS));

					if (Camera.nCodecId_temp == AVFrame.MEDIA_CODEC_VIDEO_MPEG4) {
						txtFrameRate.setText(String
								.valueOf(MediaCodecMonitor_MPEG4.keepFPS));
					} else if (Camera.nCodecId_temp == AVFrame.MEDIA_CODEC_VIDEO_H264) {
						txtFrameRate.setText(String
								.valueOf(MediaCodecMonitor.keepFPS));
					} else {
						txtFrameRate.setText(String.valueOf(Monitor.keepFPS));
					}
				}

				if (txtBitRate != null)
					txtBitRate.setText(String.valueOf(mVideoBPS) + "Kbps");

				if (txtOnlineNumber != null)
					txtOnlineNumber.setText(String.valueOf(mOnlineNm));

				if (txtFrameCount != null)
					txtFrameCount.setText(String.valueOf(mFrameCount));

				if (txtIncompleteFrameCount != null)
					txtIncompleteFrameCount.setText(String
							.valueOf(mIncompleteFrameCount));

				if (txtConnectionMode != null)
					txtConnectionMode
							.setText(getSessionMode(mCamera != null ? mCamera
									.getSessionMode() : -1)
									+ " C: "
									+ IOTCAPIs.IOTC_Get_Nat_Type()
									+ ", D: "
									+ stSInfo.NatType
									+ ",R"
									+ mCamera.getbResend());

				if (txtRecvFrmPreSec != null)
					txtRecvFrmPreSec.setText(String.valueOf(mCamera
							.getRecvFrmPreSec()));

				if (txtDispFrmPreSeco != null) {
					// txtDispFrmPreSeco.setText(String.valueOf(mCamera.getDispFrmPreSec()));
					txtDispFrmPreSeco.setText(String
							.valueOf(MediaCodecMonitor.mDecodeCount_temp));
				}

				if (txtPerformance != null)
					txtPerformance
							.setText(getPerformance((int) (((float) MediaCodecMonitor.mDecodeCount_temp / (float) mCamera
									.getRecvFrmPreSec()) * 100)));

				break;

			case STS_SNAPSHOT_SCANED:

				Toast.makeText(LiveViewActivity.this,
						getText(R.string.tips_snapshot_ok), Toast.LENGTH_SHORT)
						.show();

				break;

			case Camera.CONNECTION_STATE_CONNECTING:

				if (!mCamera.isSessionConnected()
						|| !mCamera.isChannelConnected(mSelectedChannel)) {

					mConnStatus = getText(R.string.connstus_connecting)
							.toString();

					if (txtConnectionStatus != null)
						txtConnectionStatus.setText(mConnStatus);
				}

				break;

			case Camera.CONNECTION_STATE_CONNECTED:

				if (mCamera.isSessionConnected()
						&& avChannel == mSelectedChannel
						&& mCamera.isChannelConnected(mSelectedChannel)) {

					mConnStatus = getText(R.string.connstus_connected)
							.toString();

					if (txtConnectionStatus != null)
						txtConnectionStatus.setText(mConnStatus);

					updateAudioStatus();
				}

				break;

			case Camera.CONNECTION_STATE_DISCONNECTED:

				mConnStatus = getText(R.string.connstus_disconnect).toString();

				if (txtConnectionStatus != null)
					txtConnectionStatus.setText(mConnStatus);

				updateAudioStatus();

				break;

			case Camera.CONNECTION_STATE_UNKNOWN_DEVICE:

				mConnStatus = getText(R.string.connstus_unknown_device)
						.toString();

				if (txtConnectionStatus != null)
					txtConnectionStatus.setText(mConnStatus);

				updateAudioStatus();

				break;

			case Camera.CONNECTION_STATE_TIMEOUT:

				if (mCamera != null) {

					mCamera.stopSpeaking(mSelectedChannel);
					mCamera.stopListening(mSelectedChannel);
					mCamera.stopShow(mSelectedChannel);
					Glog.D("www", "CONNECTION_STATE_TIMEOUT_stopShow");
					mCamera.stop(mSelectedChannel);
					mCamera.disconnect();
					mCamera.connect(mDevUID);
					mCamera.start(Camera.DEFAULT_AV_CHANNEL,
							mDevice.View_Account, mDevice.View_Password);
					mCamera.startShow(mSelectedChannel, true, mIsSoftwareDecode);
					Glog.D("www", "CONNECTION_STATE_TIMEOUT_startShow");

					mCamera.sendIOCtrl(
							Camera.DEFAULT_AV_CHANNEL,
							AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GETSUPPORTSTREAM_REQ,
							AVIOCTRLDEFs.SMsgAVIoctrlGetSupportStreamReq
									.parseContent());
					mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
							AVIOCTRLDEFs.IOTYPE_USER_IPCAM_DEVINFO_REQ,
							AVIOCTRLDEFs.SMsgAVIoctrlDeviceInfoReq
									.parseContent());
					mCamera.sendIOCtrl(
							Camera.DEFAULT_AV_CHANNEL,
							AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GETAUDIOOUTFORMAT_REQ,
							AVIOCTRLDEFs.SMsgAVIoctrlGetAudioOutFormatReq
									.parseContent());
					mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
							AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GET_TIMEZONE_REQ,
							AVIOCTRLDEFs.SMsgAVIoctrlTimeZone.parseContent());

					if (mIsListening)
						mCamera.startListening(mSelectedChannel, mIsListening);

				}

				break;

			case Camera.CONNECTION_STATE_CONNECT_FAILED:

				mConnStatus = getText(R.string.connstus_connection_failed)
						.toString();

				if (txtConnectionStatus != null)
					txtConnectionStatus.setText(mConnStatus);

				updateAudioStatus();

				break;

			case Camera.CONNECTION_STATE_WRONG_PASSWORD:

				mConnStatus = getText(R.string.connstus_wrong_password)
						.toString();

				if (txtConnectionStatus != null)
					txtConnectionStatus.setText(mConnStatus);

				break;

			case AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GETSUPPORTSTREAM_RESP:

				updateAudioStatus();

				break;
			}

			super.handleMessage(msg);
		}
	};

	@Override
	public void OnSnapshotComplete() {
		// TODO Auto-generated method stub
		MediaScannerConnection.scanFile(LiveViewActivity.this,
				new String[] { mFilePath.toString() },
				new String[] { "image/*" },
				new MediaScannerConnection.OnScanCompletedListener() {
					public void onScanCompleted(String path, Uri uri) {
						Log.i("ExternalStorage", "Scanned " + path + ":");
						Log.i("ExternalStorage", "-> uri=" + uri);
						Message msg = handler.obtainMessage();
						msg.what = STS_SNAPSHOT_SCANED;
						handler.sendMessage(msg);
					}
				});
	}


	@Override
	public void receiveFrameDataForMediaCodec(Camera camera, int avChannel,
											  byte[] buf, int length, int pFrmNo, byte[] pFrmInfoBuf,
											  boolean isIframe, int codecId) {
		// TODO Auto-generated method stub

		if (mHardMonitor != null
				&& mHardMonitor.getClass().equals(MediaCodecMonitor.class)) {

			if((mVideoWidth != ((MediaCodecMonitor) mHardMonitor).getVideoWidth() ||
				mVideoHeight != ((MediaCodecMonitor) mHardMonitor).getVideoHeight())) {

				mVideoWidth = ((MediaCodecMonitor) mHardMonitor).getVideoWidth();
				mVideoHeight = ((MediaCodecMonitor) mHardMonitor).getVideoHeight();

				reScaleMonitor();
			}
		}
	}

	@Override
	public void Unavailable() {
		if(unavailable)
			return;

		unavailable = true;
		mSoftCodecCurrent = true;

		SharedPreferences settings = mContext.getSharedPreferences("CodecConfig", 0);
		settings.edit().putBoolean("isSoftCodec", unavailable).commit();

		if (mSoftMonitor != null) {
			mSoftMonitor.deattachCamera();
		}
		if (mHardMonitor != null) {
			mHardMonitor.deattachCamera();
		}

		Configuration cfg = getResources().getConfiguration();

		if (cfg.orientation == Configuration.ORIENTATION_PORTRAIT) {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {

					if(mCamera != null) {

						mCamera.stopShow(mSelectedChannel);
						handler.postDelayed(new Runnable() {
							@Override
							public void run() {
								mCamera.startShow(mSelectedChannel, true, true);
								setupPortraitView(true);
							}
						}, 1000);

					}

				}
			});
		}
		else if (cfg.orientation == Configuration.ORIENTATION_LANDSCAPE) {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {

					if(mCamera != null) {

						mCamera.stopShow(mSelectedChannel);
						handler.postDelayed(new Runnable() {
							@Override
							public void run() {
								mCamera.startShow(mSelectedChannel, true, true);
								setupLandscapeView(true);
							}
						}, 1000);

					}

				}
			});
		}
	}

	@Override
	public void receiveSnapshot(Bitmap bmp) {
		// TODO Auto-generated method stub
		try {
			FileOutputStream fos = new FileOutputStream(mFilePath);
			bmp.compress(Bitmap.CompressFormat.JPEG, 90, fos);
			fos.flush();
			fos.close();
			addImageGallery(new File(mFilePath));

			runOnUiThread(new Runnable() {
				public void run() {
					Toast.makeText(LiveViewActivity.this,
							getText(R.string.tips_snapshot_ok),
							Toast.LENGTH_SHORT).show();
				}
			});

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			runOnUiThread(new Runnable() {
				public void run() {
					Toast.makeText(LiveViewActivity.this,
							getText(R.string.tips_snapshot_failed),
							Toast.LENGTH_SHORT).show();
				}
			});

		}
	}

	@Override
	public void zoomSurface(final float scale) {

		Display display = getWindowManager().getDefaultDisplay();
		Point size = new Point();
		display.getSize(size);
		final int screenWidth = size.x;
		final int screenHeight = size.y;

		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub

				SurfaceView surfaceView = (SurfaceView) mHardMonitor;
				LayoutParams lp = (LayoutParams) surfaceView.getLayoutParams();

				lp.width = (int) (mMiniVideoWidth * scale);
				lp.height = (int) (mMiniVideoHeight * scale);
				surfaceView.setLayoutParams(lp);

				lp = (LayoutParams) surfaceView.getLayoutParams();
				LinearLayout layout = (LinearLayout) surfaceView.getParent();

				if(lp.width <= layout.getWidth())
				{
					lp.leftMargin = 0;
				}else{

					if(surfaceView.getLeft() > 0)
					{
						lp.leftMargin -= Math.abs(surfaceView.getLeft());
					}else if(surfaceView.getRight() < layout.getWidth())
					{
						lp.leftMargin += (layout.getWidth() -surfaceView.getRight());
					}
				}

				if(lp.height <= layout.getHeight())
				{
					lp.topMargin = 0;
				}else{

					if(surfaceView.getTop()  >0)
					{
						lp.topMargin -= Math.abs(surfaceView.getTop());
					}else if(surfaceView.getBottom() < layout.getHeight())
					{
						lp.topMargin +=(layout.getHeight() -surfaceView.getBottom());
					}
				}

				surfaceView.setLayoutParams(lp);
			}
		});
	}
	
	private void reScaleMonitor() {
		
		
		if(mVideoHeight == 0 || mVideoWidth == 0)
			return;
		
		
		Display display = getWindowManager().getDefaultDisplay();
		Point size = new Point();
		display.getSize(size);
		final int screenWidth = size.x;
		final int screenHeight = size.y;

		
		final SurfaceView surfaceView;
		if(mSoftCodecCurrent){
			surfaceView = (SurfaceView) mSoftMonitor;
		}else{
			surfaceView = (SurfaceView) mHardMonitor;
		}
		
		if(surfaceView == null)
			return;
		
		
		/**
		 * portrait mode
		 */
		if(screenHeight >= screenWidth) {
			
			mFrameMode = FrameMode.PORTRAIT;
			surfaceView.getLayoutParams().width = screenWidth;
			surfaceView.getLayoutParams().height = (int) (screenWidth * mVideoHeight / (float)mVideoWidth);
			
			
		}
		/**
		 * landscape mode
		 */
		else {
			
			int actionBarHeight = getSupportActionBar().getHeight();
			
			if(surfaceView.getLayoutParams().width > screenWidth) {
				/**
				 * up down space
				 */
				mFrameMode = FrameMode.LANDSCAPE_COL_MAJOR;
				surfaceView.getLayoutParams().width = screenWidth;
				surfaceView.getLayoutParams().height = (int) (screenWidth * mVideoHeight / (float)mVideoWidth);
				final int scrollViewHeight = surfaceView.getLayoutParams().height;
				handler.post(new Runnable() {
					@Override
					public void run() {
						if(mSoftCodecCurrent)
							mSoftMonitorLayout.setPadding(0, (screenHeight - scrollViewHeight) / 2, 0, 0);
						else
							mHardMonitorLayout.setPadding(0, (screenHeight - scrollViewHeight) / 2, 0, 0);
					}
				});
				
			}
			else {
				/**
				 * left right space
				 */
				mFrameMode = FrameMode.LANDSCAPE_ROW_MAJOR;
				surfaceView.getLayoutParams().height = screenHeight - actionBarHeight;
				surfaceView.getLayoutParams().width = (int) ((screenHeight - actionBarHeight) * mVideoWidth / (float)mVideoHeight);
				final int scrollViewWidth = surfaceView.getLayoutParams().width;
				handler.post(new Runnable() {
					@Override
					public void run() {
						if(mSoftCodecCurrent)
							mSoftMonitorLayout.setPadding((screenWidth - scrollViewWidth) / 2, 0, 0, 0);
						else
							mHardMonitorLayout.setPadding((screenWidth - scrollViewWidth) / 2, 0, 0, 0);
					}
				});
			}
		}

		mMiniVideoHeight = surfaceView.getLayoutParams().height;
		mMiniVideoWidth = surfaceView.getLayoutParams().width;
		
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				surfaceView.setLayoutParams(surfaceView.getLayoutParams());
			}
		});

		
	}

	
	private Point mStartPoint = new Point();
//	public void touchSurface(MotionEvent event) {
//		
//		if(event.getPointerCount()!=1)
//		{
//			mStartPoint=null;
//			return ;
//		};
//		
//		Log.d("test", "" + event.getAction());
//		switch(event.getAction())
//		{
//			case MotionEvent.ACTION_DOWN:
//			{
//				mStartPoint=new Point((int)event.getX(), (int)event.getY());
//			}
//			break;
//			case MotionEvent.ACTION_UP:
//			{
//				
//			}
//			break;
//			case MotionEvent.ACTION_MOVE:
//			{
//				if(mStartPoint==null)return;
//				
//				SurfaceView surfaceView = (SurfaceView) mHardMonitor;
//				LinearLayout layout = (LinearLayout) surfaceView.getParent();
//				LinearLayout.LayoutParams lp = (LayoutParams) surfaceView.getLayoutParams();
//
//				if(surfaceView.getWidth() <= layout.getWidth())
//				{
//					lp.leftMargin = 0;
//				}else{
//
//					int moveX = (int) (event.getX() - mStartPoint.x);
//					
//					if(surfaceView.getLeft() + moveX > 0)
//					{
//						lp.leftMargin += Math.abs(surfaceView.getLeft());
//					}else if(surfaceView.getRight() + moveX < layout.getWidth())
//					{
//						lp.leftMargin += (layout.getWidth() -surfaceView.getRight());
//					}else{
//						lp.leftMargin += moveX;
//					}
//				}
//
//				if(surfaceView.getHeight() <= layout.getHeight())
//				{
//					lp.topMargin = 0;
//				}else{
//
//					int moveY = (int) (event.getY() - mStartPoint.y);
//					
//					if(surfaceView.getTop() + moveY >0)
//					{
//						lp.topMargin += Math.abs(surfaceView.getTop());
//					}else if(surfaceView.getBottom() + moveY < layout.getHeight())
//					{
//						lp.topMargin +=(layout.getHeight() -surfaceView.getBottom());
//					}else{
//						lp.topMargin += moveY;
//					}
//				}
//				surfaceView.setLayoutParams(lp);
//			}
//			break;
//		}
//	}

	@Override
	public void monitorIsReady() {
		// TODO Auto-generated method stub
		
	}

	/*
	 * @Override public void onMediaScannerConnected() {
	 * conn.scanFile(mScanPath, FILE_TYPE); }
	 * 
	 * @Override public void onScanCompleted(String path, Uri uri) { try { if
	 * (mOpenAlbum) { if (uri != null) { Intent intent = new
	 * Intent(Intent.ACTION_VIEW); //intent.setData(uri); Uri hacked_uri =
	 * Uri.parse("file://" + uri.getPath()); intent.setDataAndType(uri,
	 * FILE_TYPE); startActivity(intent); } } else {
	 * System.out.println("Snapshot:" + path + " ok");
	 * //Toast.makeText(LiveViewActivity.this,
	 * getText(R.string.tips_snapshot_ok), Toast.LENGTH_SHORT).show(); Message
	 * msg = handler.obtainMessage(); msg.what = STS_SNAPSHOT_SCANED;
	 * handler.sendMessage(msg); } } finally { conn.disconnect(); conn = null; }
	 * }
	 */
	
	
}
